package com.LachesismStorm.lachesism.websocket;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.LachesismStorm.lachesism.core.util.AESUtil;
import com.LachesismStorm.lachesism.core.util.LachesismTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author lachesism
 * @Date 2023-07-06 20:54
 **/
@Slf4j
@ServerEndpoint(value = "/chatRoom")
@Component
public class WebSocketService {


    //用于保存WebSocket连接对象
    public static ConcurrentHashMap<Integer, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("加入了一个新session");
        Map<String, Object> userProperties = session.getUserProperties();
        int size = sessionMap.size();
        userProperties.put("index", size);
        sessionMap.put(size, session);
        sendMessage("ok", session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        Map<String, Object> userProperties = session.getUserProperties();
        Integer index = (Integer) userProperties.get("index");
        sessionMap.remove(index);
        String nickName = (String) userProperties.get("nickName");
        notification("用户：" + nickName + "离开了");

    }

    /**
     * 接收消息
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        if ("ping".equals(message)) {
            sendMessage("pong", session);
            return;
        }
        //把字符串转换成JSON
        message = LachesismTools.decrypt(message);
        JSONObject json = JSONUtil.parseObj(message);
        Map<String, Object> userProperties = session.getUserProperties();
        if (!userProperties.containsKey("nickName")) {
            userProperties.put("nickName", json.getStr("nickName"));
            notification("用户:" + json.getStr("nickName") + " 加入了聊天");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println(error);
        System.out.println("websocket:" + session + "发送错误了");
    }

    /**
     * 通知
     */
    private static void notification(String message) {
        for (Session session : sessionMap.values()) {
            session.getAsyncRemote().sendText("/:notification/" + message);
        }

    }

    /**
     * 广播
     */
    public static void broadcast(String message) {
        for (Session session : sessionMap.values()) {
            session.getAsyncRemote().sendText(message);
        }

    }

    /**
     * 封装发送消息给客户端
     */
    private void sendMessage(String message, Session session) {
        session.getAsyncRemote().sendText(message);
    }
}


